package com.superman.mvpframe.client.history;

import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.google.web.bindery.event.shared.SimpleEventBus;

/**
 * html5历史栈实现类
 * 
 * @author superman
 * @version 2018年7月5日下午10:29:51
 */
public class Html5HistorianImpl implements IHtml5Historian {

	private EventBus eventBus = new SimpleEventBus();

	/**
	 * 构造方法
	 * 
	 * @author superman
	 * @version 2018年7月5日 下午10:29:29
	 */
	public Html5HistorianImpl() {
		bind();
	}

	@Override
	public HandlerRegistration addPopStateHandler(PopStateHandler handler) {
		return eventBus.addHandler(PopStateEvent.getType(), handler);

	}

	@Override
	public native void back() /*-{
								$wnd.history.back();
								}-*/;

	private native void bind() /*-{
								var that = this;
								
								var f = function(event) {
								var data = "";
								if (event.state != null) {
								data = event.state;
								}
								that.@com.superman.mvpframe.client.history.Html5HistorianImpl::onPopState(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)(data, event.title, event.url);
								
								};
								
								$wnd.addEventListener('popstate', $entry(f));
								
								}-*/;

	protected native String decodeFragment(String encodedFragment) /*-{
																	// decodeURI() does *not* decode the '#' character.
																	return decodeURI(encodedFragment.replace("%23", "#"));
																	}-*/;

	protected native String encodeFragment(String fragment) /*-{
															// encodeURI() does *not* encode the '#' character.
															return encodeURI(fragment).replace("#", "%23");
															}-*/;

	@Override
	public native void forward() /*-{
									$wnd.history.forward();
									}-*/;

	@Override
	public native void go(int number) /*-{
										$wnd.history.go(number);
										}-*/;

	@Override
	public native int length() /*-{
								return $wnd.history.length;
								}-*/;

	// called from js
	protected void onPopState(String data, String title, String url) {
		eventBus.fireEvent(new PopStateEvent(data, title, url));
	}

	@Override
	public native void pushState(String data, String title, String url) /*-{
																		$wnd.history.pushState(data, title, url);
																		}-*/;

	@Override
	public native void replaceState(String data, String title, String url) /*-{
																			$wnd.history.replaceState(data, title, url);
																			}-*/;

}
